package com.su.fileupload.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.su.fileupload.entity.SysChunk;
import com.su.fileupload.entity.SysFileList;
import com.su.fileupload.mapper.SysChunkMapper;
import com.su.fileupload.service.ISysChunkService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.su.fileupload.service.ISysFileListService;
import com.su.fileupload.vo.request.FileChunkRequest;
import com.su.fileupload.vo.response.FileChunkCheckResponse;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 文件分片记录表 服务实现类
 * </p>
 *
 * @author susj
 * @since 2023-08-13
 */
@Service
public class SysChunkServiceImpl extends ServiceImpl<SysChunkMapper, SysChunk> implements ISysChunkService {

    @Resource
    private ISysFileListService sysFileListService;

    @Override
    public FileChunkCheckResponse checkFileChunk(FileChunkRequest fileChunkRequest) {
        SysFileList sysFileList = sysFileListService.getByMd5(fileChunkRequest.getIdentifier());
        // 根据md5值查询文件是否已经上传过、则可以秒传
        if(Objects.nonNull(sysFileList)){
            return FileChunkCheckResponse.builder().skipUpload(Boolean.TRUE).build();
        }
        // 先检查文件是否已上传
        List<SysChunk> chunkList = this.getChunkList(fileChunkRequest.getIdentifier());
        List<Integer> chunkNumberList = chunkList.stream().mapToInt(SysChunk::getChunkNumber).boxed().collect(Collectors.toList());
        return FileChunkCheckResponse.builder().skipUpload(false).uploaded(chunkNumberList).build();
    }


    @Override
    public List<SysChunk> getChunkList(String identifier) {
        LambdaQueryWrapper<SysChunk> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysChunk::getIdentifier, identifier);
        return this.list(queryWrapper);
    }

    @Override
    public void removeByFileIdentifier(String identifier) {
        LambdaQueryWrapper<SysChunk> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysChunk::getIdentifier, identifier);
        this.remove(queryWrapper);
    }
}
